package com.atguigu.springcloud.mylb;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 自定义类似ribbon的负载均衡轮询算法
 */
@Component
public class MyLB {
	//定义访问次数
	private AtomicInteger count = new AtomicInteger(0);
	
	//注入discoveryclient
	@Autowired
	private DiscoveryClient discoveryClient;
	
	public Integer choose(){
		int count1 = count.get();
		while (true) {
			if (count.weakCompareAndSet(count1,count1 + 1)) {
				return count.get();
			};
		}
	}
	
	//获取服务
	public ServiceInstance getService(String serviceID){
		List<ServiceInstance> instances = discoveryClient.getInstances(serviceID);
		return instances.get(choose() % instances.size());
	}
}
